package com.tarena.dang.daos.impl;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.tarena.dang.daos.UserDAO;
import com.tarena.dang.pojos.User;
import com.tarena.dang.utils.DBUtils;

public class JdbcUserDAO implements UserDAO {
	private static final String SAVE = "insert into d_user "
			+ "(email,nickname,password,user_integral,"
			+ "is_email_verify,email_verify_code,last_login_time,"
			+ "last_login_ip) values (?,?,?,?,?,?,?,?)";

	private static final String update = "update d_user "
			+ "set email=?,nickname=?,password=?,user_integral=?,"
			+ "is_email_verify=?,email_verify_code=?,"
			+ "last_login_time=?,last_login_ip=? where id=?";

	public void save(User user) throws SQLException {
		PreparedStatement prep = DBUtils.getConnection().prepareStatement(SAVE,
				Statement.RETURN_GENERATED_KEYS);
		prep.setString(1, user.getEmail());
		prep.setString(2, user.getNickname());
		prep.setString(3, user.getPassword());
		prep.setInt(4, user.getUserIntegral());
		String isVerify = user.isEmailVerify() ? "Y" : "N";
		prep.setString(5, isVerify);
		prep.setString(6, user.getEmailVerifyCode());
		prep.setLong(7, user.getLastLoginTime());
		prep.setString(8, user.getLastLoginIp());
		prep.executeUpdate();
		ResultSet rs = prep.getGeneratedKeys();
		rs.next();
		user.setId(rs.getInt(1));

		DBUtils.closeConnection();
	}

	public void update(User user) throws SQLException {
		PreparedStatement pst = DBUtils.getConnection()
				.prepareStatement(update);
		pst.setString(1, user.getEmail());
		pst.setString(2, user.getNickname());
		pst.setString(3, user.getPassword());
		pst.setInt(4, user.getUserIntegral());
		String isVerify = user.isEmailVerify() ? "Y" : "N";
		pst.setString(5, isVerify);
		pst.setString(6, user.getEmailVerifyCode());
		pst.setLong(7, user.getLastLoginTime());
		pst.setString(8, user.getLastLoginIp());
		pst.setInt(9, user.getId());
		pst.executeUpdate();

		DBUtils.closeConnection();
	}

	public User findByEmail(String email) throws SQLException {
		String sql = "select * from d_user where email=?";
		PreparedStatement pst;
		pst = DBUtils.getConnection().prepareStatement(sql);
		pst.setString(1, email);
		ResultSet rs = pst.executeQuery();
		if (!rs.next())
			return null;
		User user = new User();

		user.setId(rs.getInt("id"));
		user.setEmail(rs.getString("email"));
		user.setNickname(rs.getString("nickname"));
		user.setPassword(rs.getString("password"));
		user.setUserIntegral(rs.getInt("user_integral"));
		user.setEmailVerify(rs.getString("is_email_verify").equals("Y") ? true
				: false);
		user.setEmailVerifyCode(rs.getString("email_verify_code"));
		user.setLastLoginTime(rs.getLong("last_login_time"));
		user.setLastLoginIp(rs.getString("last_login_ip"));

		DBUtils.closeConnection();
		return user;

	}
}
